package com.example.demo.config.datasource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;

/**
 * Mysql数据源配置类
 *
 * @author Frankiegg
 * @date 2018-4-15
 * @version
 */
@Configuration
@MapperScan(basePackages = {"com.example.demo.mapper.mysqlMapper"}, sqlSessionFactoryRef = "mysqlSessionFactory")
public class MysqlConfig {
    @Autowired
    @Qualifier("mysqlDB")
    private DataSource ds1;

    @Primary
    @Bean
    public SqlSessionFactory mysqlSessionFactory() throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(ds1); // 使用mysql数据源, 连接mysql库

        return factoryBean.getObject();

    }

    @Primary
    @Bean
    public SqlSessionTemplate sqlSessionTemplate1() throws Exception {
        SqlSessionTemplate template = new SqlSessionTemplate(mysqlSessionFactory()); // 使用上面配置的Factory
        return template;
    }
}
